import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {LoginService} from '../shared/login.service';
import {Router} from '@angular/router';
import {MatSnackBar} from '@angular/material';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  // @Input() username: string;
  // @Input() password: string;

  loginForm: FormGroup;
  constructor(
    private loginService: LoginService,
    private router: Router,
    private snackBar: MatSnackBar,
    private fb: FormBuilder) {
    this.loginForm = this.fb.group({
      'username': ['', Validators.required],
      'password': ['', Validators.required]
    });
  }

  ngOnInit() {
  }
  login() {
    const credentials = this.loginForm.value;
    this.loginService.login(credentials.username, credentials.password).subscribe((loginResult: any) => {
      if (loginResult) {
        window.sessionStorage.setItem('accesstoken', loginResult.accesstoken);
        // alert(loginResult.accesstoken);
        this.router.navigate(['dashboard']);
      } else {
        this.openSnackBar('登入错误，请检查用户名和密码！', '');
        console.log('login failed, please check username or password!');
      }
    }, (loginResult: any) => {
      this.openSnackBar('登入失败', '');
      console.log('login error');
    });
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
}
